<?
# 태터툴즈 1.1 이상 용 Draco 카운터 Ver 3.02
# 제작자 : Draco 
# 제작일 : 2008. 2. 25
# 中文化： http://Fall-Leaf.Net / 2009-01-05
# 문의 : http://draco.pe.kr 

function ShowDracoCounter_DataSet($data){
	requireComponent('Textcube.Function.misc');
	if(!is_integer(intval($data['how_day']))) return false;
	$cfg = misc::fetchConfigVal($data);
	return true;
}

function tcDateToTime($d) // 블로그 방문자숫자를 시간 문자열로 변환
{
		$y = intval($d/10000);
		$m = intval(($d%10000)/100);
		$d = $d%100;
					
		return ("$y-$m-$d 00:00:00");
}
		
function dateDiff($d1, $d2) // 날짜 차이를 계산
{
	return floor((strtotime($d2) - strtotime($d1))/60/60/24);
}	

function ShowDracoCounter($parameter){

	global $database, $owner, $blogURL, $pluginURL, $configVal;
	requireComponent('Textcube.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	if(!is_null($data) && array_key_exists('how_day', $data)){
		$how_day = $data['how_day'];
	} else {
		$how_day = '30';
	}
	if(!is_null($data) && array_key_exists('cut_peak', $data)){
		$cut_peak = $data['cut_peak'];
	} else {
		$cut_peak = 'true';
	}
	if(!is_null($data) && array_key_exists('view_marker', $data)){
		$view_marker = $data['view_marker'];
	} else {
		$view_marker = 'true';
	}
	if(!is_null($data) && array_key_exists('view_grid', $data)){
		$view_grid = $data['view_grid'];
	} else {
		$view_grid = 'false';
	}	
	if(!is_null($data) && array_key_exists('graph_barwidth', $data)){
		$graph_barwidth = $data['graph_barwidth'];
	} else {
		$graph_barwidth = '5';
	}
	if(!is_null($data) && array_key_exists('graph_color', $data)){
		$graph_color = $data['graph_color'];
	} else {
		$graph_color = '#577EE1';
	}
	if(!is_null($data) && array_key_exists('line_thickness', $data)){
		$line_thickness = $data['line_thickness'];
	} else {
		$line_thickness = '2';
	}	
	if(!is_null($data) && array_key_exists('line_blank', $data)){
		$line_blank = $data['line_blank'];
	} else {
		$line_blank = 'false';
	}		
	if(!is_null($data) && array_key_exists('graph_backcolor', $data)){
		$graph_backcolor = $data['graph_backcolor'];
	} else {
		$graph_backcolor = '#FFFFFF';
	}
	if(!is_null($data) && array_key_exists('graph_fillcolor', $data)){
		$graph_fillcolor = $data['graph_fillcolor'];
	} else {
		$graph_fillcolor = '#F4F7FF';
	}	
	if(!is_null($data) && array_key_exists('graph_highcolor', $data)){
		$graph_highcolor = $data['graph_highcolor'];
	} else {
		$graph_highcolor = '#FF0000';
	}
	if(!is_null($data) && array_key_exists('disp_y', $data)){
		$disp_y = $data['disp_y'];
	} else {
		$disp_y = 'true';
	}
	if(!is_null($data) && array_key_exists('disp_x', $data)){
		$disp_x = $data['disp_x'];
	} else {
		$disp_x = 'true';
	}
	if(!is_null($data) && array_key_exists('xy_color', $data)){
		$xy_color = $data['xy_color'];
	} else {
		$xy_color = '#cccccc';
	}


#------------------------------------------------------------------------------------------
## 1.5이전인지 이후인지 체크
    $query = ("SHOW COLUMNS FROM `".$database['prefix']."DailyStatistics` LIKE 'blogid'");
    $result = mysql_query($query) or die("版本檢查錯誤 : ".mysql_error());
	$rarray = mysql_fetch_array($result);
	if (NULL == $rarray[0]) $blogid_col = "owner";
	else $blogid_col = "blogid";

# 날짜 계산
		
		$now_date = strtotime("now"); 
		$old_date = strtotime("-".($how_day-1)." days"); 
		$now_day = date('Ymd', $now_date); 
		$old_day = date('Ymd', $old_date);
		$yester_day = date('Ymd', strtotime("-1 day")); 

# 최대 방문자 계산

		$max_query = "SELECT `visits` FROM `".$database['prefix']."DailyStatistics` WHERE `".$blogid_col."` =".$owner."  and date between ".$old_day." and ".$now_day." ORDER BY `visits` DESC LIMIT 1";
		$max_result = mysql_query($max_query) or die("查詢失敗1 : " . mysql_error());

		$max_data=mysql_fetch_array($max_result);
		$max_data['visits']=stripslashes($max_data['visits']); 

# 평균 방문자 계산

		$avg_query = "SELECT AVG(visits) FROM `".$database['prefix']."DailyStatistics` WHERE `".$blogid_col."` =".$owner."  and date between ".$old_day." and ".$now_day;
		$avg_result = mysql_query($avg_query) or die("查詢失敗2 : " . mysql_error());

		$avg_data=mysql_fetch_array($avg_result);
		$avg=round($avg_data['AVG(visits)']);

# 평균의 2배보다 많은 수치를 제외하고 계산
		$cut_line = $avg*2;

		$cut_query = "SELECT MAX(visits) FROM `".$database['prefix']."DailyStatistics` WHERE `".$blogid_col."` =".$owner." and `visits` <= ".$cut_line." and date between ".$old_day." and ".$now_day;
		$cut_result = mysql_query($cut_query) or die("查詢失敗3 : " . mysql_error());

		$cut_data=mysql_fetch_array($cut_result);
		$cut_line=round($cut_data['MAX(visits)']);

		if($cut_peak == 'true') $graph_max = $cut_line;
		else $graph_max = $max_data['visits'];
		
#최대 날짜, 최소 날짜
		$high_query = "SELECT `date` FROM `".$database['prefix']."DailyStatistics` WHERE `".$blogid_col."` =".$owner."  and date between ".$old_day." and ".$now_day." ORDER BY `visits` DESC LIMIT 1";
		$high_result = mysql_query($high_query) or die("查詢失敗4 : " . mysql_error());
		$high_data=mysql_fetch_array($high_result);
		$high_date=$high_data['date'];
		
		$low_query = "SELECT `date` FROM `".$database['prefix']."DailyStatistics` WHERE `".$blogid_col."` =".$owner."  and date between ".$old_day." and ".$yester_day." ORDER BY `visits` ASC LIMIT 1";
		$low_result = mysql_query($low_query) or die("查詢失敗5 : " . mysql_error());
		$low_data=mysql_fetch_array($low_result);
		$low_date=$low_data['date'];		
		
		$high_diff = dateDiff(tcDateToTime($old_day),tcDateToTime($high_date));
		$low_diff = dateDiff(tcDateToTime($old_day),tcDateToTime($low_date));


# 실제 방문자수 리스팅
		$dcount_query = "SELECT `date` , `visits` FROM `".$database['prefix']."DailyStatistics` WHERE `".$blogid_col."` =".$owner." and date between ".$old_day." and ".$now_day." ORDER BY `date` ASC LIMIT ".$how_day; 
		$dcount_result = mysql_query($dcount_query) or die("查詢失敗6 : " . mysql_error());

# 그래프 폭
		$graph_width = ($how_day-1)*$graph_barwidth;
		
# 메인 부분 HTML 처리
		$target = "
		<style type='text/css'>

#dhtmltooltip{
				position: absolute;
				border: 1px solid #ccc;
				padding: 0px 5px;
				visibility: hidden;
				z-index: 100;
				color : #000;
				font-size: 11px;
				text-align: left;
}

#tooltip_ul{
				list-style-type:none;
				margin: 0px  !important;
				padding : 0 !important;
}

#tooltip_ul li{
				margin: 4px  !important;
				padding: 0px 0px 2px 18px  !important;
				line-height: 16px !important;
}

#tooltip_date{
				font-size: 12px;
				color : #000060;
				font-weight: bold;
				background : url(".$pluginURL."/date-plain.png) no-repeat 0px 50% !important;
				border-bottom-width: 1px !important;
				border-top-style: none !important;
				border-right-style: none !important;
				border-bottom-style: solid !important;
				border-left-style: none !important;
				border-bottom-color: #EEE !important;
}

#tooltip_post{
				background : url(".$pluginURL."/doc-option-edit.png) no-repeat 0px 50% !important;
				border : none  !important; 
}

#tooltip_guest{
				background : url(".$pluginURL."/user-plain-blue_mod.png) no-repeat 0px 50% !important;
				border : none  !important; 
}

#draco_counter {
				margin: 0px !important;
				padding: 0px !important;";
				$target .= "
				font-family: Tahoma; 
				font-size: 9px;";
				if(isset($xy_color)) {$target .="color : ".$xy_color.";";}
			$target .="
}

#draco_counter_y p{
				display: block  !important;
				margin: 0px !important;
				line-height: 12px !important;
}

#draco_counter_x p{
				display: inline  !important;
				margin: 0px !important;
				line-height: 12px !important;
				padding: 0px !important;
}

#draco_counter_y{
				width: 30px;
				height: 100px;
				text-align: right;
}

#draco_counter_y_mid{
				padding: 34px 0px 46px 0px;
}

#draco_counter_x {
				width : ".($graph_width)."px;
				height: 12px;
				margin: 0px !important;
				padding: 0px !important;
}

#draco_counter_x1{
				float: left !important;
				text-align: left;
}

#draco_counter_x2{
				float: right !important;
				text-align: right;
}

		</style>

		<div id='dhtmltooltip'></div>

		<script type='text/javascript'>

		/***********************************************
		* Cool DHTML tooltip script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
		* This notice MUST stay intact for legal use
		* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
		***********************************************/

		var offsetxpoint=0 
		var offsetypoint=20 
		var ie=document.all
		var ns6=document.getElementById && !document.all
		var enabletip=false
		if (ie||ns6)
		var tipobj=document.all? document.all['dhtmltooltip'] : document.getElementById? document.getElementById('dhtmltooltip') : ''

		function ietruebody(){
		return (document.compatMode && document.compatMode!='BackCompat')? document.documentElement : document.body
}

		function ddrivetip(thetext, thecolor, thewidth){
		if (ns6||ie){
		if (typeof thewidth!='undefined') tipobj.style.width=thewidth+'px'
		if (typeof thecolor!='undefined' && thecolor!='') tipobj.style.backgroundColor=thecolor
		tipobj.innerHTML=thetext
		enabletip=true
		return false
}
}

		function positiontip(e){
		if (enabletip){
		var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
		var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
		var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
		var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20

		var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000

		if (rightedge<tipobj.offsetWidth)
		tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+'px' : window.pageXOffset+e.clientX-tipobj.offsetWidth+'px'
		else if (curX<leftedge)
		tipobj.style.left='5px'
		else
		tipobj.style.left=curX+offsetxpoint+'px'

		if (bottomedge<tipobj.offsetHeight)
		tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+'px' : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+'px'
		else
		tipobj.style.top=curY+offsetypoint+'px'
		tipobj.style.visibility='visible'
}
}

		function hideddrivetip(){
		if (ns6||ie){
		enabletip=false
		tipobj.style.visibility='hidden'
		tipobj.style.left='-1000px'
		tipobj.style.backgroundColor=''
		tipobj.style.width=''
}
}

		function dc_draw(obj, thetxt){
			obj.style.backgroundColor='".$graph_highcolor."';
			ddrivetip(thetxt,'#fff', 135);
}

		function dc_hide(obj){
			obj.style.backgroundColor='';
			hideddrivetip();
}

		document.onmousemove=positiontip
		</script>
		";

		$target .= "<table border='0' cellpadding='0' cellspacing='0' id='draco_counter'><tr>";

#그래프 왼쪽 Y축
		if($disp_y=='true'){ $target .="<td  id='draco_counter_y'><p id='draco_counter_y_max'>".$max_data['visits']."</p><p id='draco_counter_y_mid'>";
			if($cut_peak == 'true') $target .= $avg;
			else $target .= round($max_data['visits']/2);
		$target .="</p></td>";
}		

		$target .= "<td><map name='draco_counter_map'>";
		$chd = "";
		$map_x = 0;
		$map_x_next = $map_x + intval($graph_barwidth/2);
		$loopcount = 0;

#그래프 그리기 반복 부분
		while($dcount_data=mysql_fetch_array($dcount_result)) 
{
# 그래프 크기 계산
		$dcount_data['visits']=stripslashes($dcount_data['visits']); 
		$graph_high = round($dcount_data['visits'] / $graph_max *95);
		if($graph_high>95) $graph_high = 95;
		else if($graph_high<0) $graph_high = 0;
		if($chd!="") $chd .= ",";
		$chd .= $graph_high.".0";

			
# 날짜 데이터 년월일로 쪼개기
		$y = intval($dcount_data['date']/10000);
		$m = intval(($dcount_data['date']%10000)/100);
		$d = $dcount_data['date']%100;

# 날짜 데이터 mktime
		$day_post1_time =  mktime(0, 0, 0, $m, $d, $y);
		$day_post2_time =  $day_post1_time + 86400;
		
# 해당 날짜에 몇개의 글을 썼나 찾기
		$day_post_query = "SELECT id FROM `".$database['prefix']."Entries` WHERE `published` >= $day_post1_time AND `published` < $day_post2_time AND `".$blogid_col."` = $owner AND  `visibility` >= 2 AND `category` > 0";
		$day_post_data = mysql_query($day_post_query) or die("查詢失敗6 : " . mysql_error());
		$day_post = mysql_num_rows($day_post_data);

# 툴팁 창 만들기
		$dcount_day = "<UL id=tooltip_ul><LI id=tooltip_date>".$y."年 ".$m."月 ".$d."日<LI id=tooltip_post>文章 ";
		if($day_post) $dcount_day .= ": ".$day_post."個";
		else $dcount_day .= "沒有";
		$dcount_day .= "<LI id=tooltip_guest>訪客 : ".$dcount_data['visits']."名</UL>";		

#이미지 맵 만들기
		if($day_post){
			$target .= "<area shape='rect' coords='$map_x,0,$map_x_next,100' href='".$blogURL."/archive/".$dcount_data['date']."' onmouseover=\"highlight(".$loopcount.");dc_draw(this, '".$dcount_day."');\" onmouseout=\"highlight(-1);dc_hide(this);\"/>";
}
		else {
			$target .= "<area shape='rect' coords='$map_x,0,$map_x_next,100' onmouseover=\"highlight(".$loopcount.");dc_draw(this, '".$dcount_day."');\" onmouseout=\"highlight(-1);dc_hide(this);\"/>";		
}
		
		$map_x = $map_x_next+1;
		$map_x_next = $map_x -1 + $graph_barwidth;

		$loopcount ++;
		$lastvisit = $dcount_data['visits'];
					
}
		
#구글 api 이미지 주소 만들기		
		$chart_img = "http://chart.apis.google.com/chart?chs=".$graph_width."x100&chd=t:".$chd."&cht=lc&chco=".str_replace("#","",$graph_color)."&chf=bg,s,".str_replace("#","",$graph_backcolor);
		
		if($view_grid=='true') $chart_img .="&chg=".(100/$how_day*7).",50";
				
		if($line_blank=='true') $chart_img .= "&chls=".$line_thickness.",".($line_thickness*2).",".$line_thickness;
		else $chart_img .= "&chls=".$line_thickness.",".($line_thickness*2).",0";
		
		if($graph_fillcolor) $chart_img .="&chm=B,".str_replace("#","",$graph_fillcolor).",0,0,0";
				
		if($view_marker=='true'){ 
			if(!$graph_fillcolor) $chart_img .="&chm=";
			else $chart_img .="|";
			$chart_img .="c,6C57E2,0,$high_diff.0,10.0|x,E25757,0,$low_diff.0,10.0";

}
		
		if($graph_fillcolor || $view_marker=='true') $chart_overimg = $chart_img."|";
		else $chart_overimg = $chart_img."&chm=";
		
		$target .= "</map><img src='$chart_img' name='d_chart' usemap='#draco_counter_map' border=0>";

		$target .= "</td></tr>";


#그래프 하단 X축
		if($disp_x=='true'){
			$target .="<tr>";
			if($disp_y=='true') $target .="<td></td>";
			$target .="<td  id='draco_counter_x'><p id='draco_counter_x1'>-$how_day days</p><p id='draco_counter_x2'> today : $lastvisit</p></td></tr>";
}

		$target .= "</table> 
			<script type='text/javascript'>
				function highlight(which){
					if(which!=-1)document.images['d_chart'].src = \"".$chart_overimg."V,".str_replace("#","",$graph_highcolor).",0,\"+which+\".0,1.0\";
					else document.images['d_chart'].src = \"".$chart_img."\";
}
			</script>";

#------------------------------------------------------------------------------------------
	return $target;
}
?>